﻿using GKQC.Common;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Services;
using System;using GKQC.Language;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using TestLeakApp;
using static GKQC.Common.Settings;

namespace GKQC.Machine
{
    public partial class FormSet1601 : Form
    {
        //SerialPort spLcr, spLc, spLc10, spBox;
        //LcrMeter19001A lcrMeter;
        /// <summary>
        /// ZR or CD-R
        /// </summary>
        string _TestItem = "CD-ZR";

        ILcrMeterAuto lcrMeter;
        IBox box;
        IBox box2;
        Form1601 form1601;
        bool _IsAdjusting = false;
        OffsetCompute1601 _OffsetCompute1601;
        UserModel _User;
        OffsetEntity1601 _EmptyOffsetEntity = new OffsetEntity1601(string.Empty);
        OffsetEntity1601 _CurrentEntity;
        LcrType _LcrType = LcrType.SX10091A;
        int boxCount = 10;

        public FormSet1601(UserModel user)
        {
            InitializeComponent(); LanguageHelper.SetControlLanguageText(this);

            try
            {
                this._User = user;
                _LcrType = GetLcrType();
                getPortBuad();
                _OffsetCompute1601 = new OffsetCompute1601();
                InitCombo();
                cboSpeed.SelectedIndex = 0;
                
                this.lcrMeter = new LcrMeter19001A();
                if (GetLcType() == LcType.SX1601_20)
                {
                    this.box = new BOX20(spBox, 1, null);
                    boxCount = _OffsetCompute1601.GetChannelCount();
                    if (boxCount == 0) boxCount = 10;
                }
                else
                    this.box = new Box(spBox, 0, null);
                this.box2 = new BOX20(spBox, 2, null);
                StartSerialPort();
                Thread.Sleep(100);
                numLcFirstDelay.Value = _OffsetCompute1601.GetLcFirstDelay();
                numLcrFirstDelay.Value = _OffsetCompute1601.GetLcrFirstDelay();
                numTestTimes.Value = _OffsetCompute1601.GetTestTimes();
                numRxTestTimes.Value = _OffsetCompute1601.GetRxTestTimes();
                numBox20Time.Value = _OffsetCompute1601.GetBox20Time();
                txtZOffset.Text = _OffsetCompute1601.GetZOffset().ToString();
                txtROffset.Text = _OffsetCompute1601.GetROffset().ToString();

                chkEnable1.Checked = _OffsetCompute1601.Enable1;
                chkEnable2.Checked = _OffsetCompute1601.Enable2;
                chkEnable3.Checked = _OffsetCompute1601.Enable3;
                chkEnable4.Checked = _OffsetCompute1601.Enable4;
                chkEnable5.Checked = _OffsetCompute1601.Enable5;
                chkEnable6.Checked = _OffsetCompute1601.Enable6;
                chkEnable7.Checked = _OffsetCompute1601.Enable7;
                chkEnable8.Checked = _OffsetCompute1601.Enable8;
                chkEnable9.Checked = _OffsetCompute1601.Enable9;
                chkEnable10.Checked = _OffsetCompute1601.Enable10;
                chkEnable11.Checked = _OffsetCompute1601.Enable11;
                chkEnable12.Checked = _OffsetCompute1601.Enable12;
                chkEnable13.Checked = _OffsetCompute1601.Enable13;
                chkEnable14.Checked = _OffsetCompute1601.Enable14;
                chkEnable15.Checked = _OffsetCompute1601.Enable15;
                chkEnable16.Checked = _OffsetCompute1601.Enable16;
                chkEnable17.Checked = _OffsetCompute1601.Enable17; 
                chkEnable18.Checked = _OffsetCompute1601.Enable18;
                chkEnable19.Checked = _OffsetCompute1601.Enable19;
                chkEnable20.Checked = _OffsetCompute1601.Enable20;

                numChannelCount.Value = _OffsetCompute1601.GetChannelCount();
            }
            catch(Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0071", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }
        }



        private void getPortBuad()
        {
            try
            {
                Settings.GetPortBuad(spLcr, Settings.MachineType.LCR);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            try
            {
                Settings.GetPortBuad(spLc, Settings.MachineType.LC);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            try
            {
                Settings.GetPortBuad(spLc10, Settings.MachineType.Lc10);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            try
            {
                Settings.GetPortBuad(spBox, Settings.MachineType.Box);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            //try
            //{
            //    Settings.GetPortBuad(spBox2, Settings.MachineType.Box2);
            //}
            //catch (Exception ex)
            //{
            //    Logger.LogError(ex);
            //}
        }
        private void InitCombo()
        {
            DataTable dt = null;
            if(_LcrType == LcrType.FE2826A)
                dt = MachineFactory.GetLcrFrequencyTable();
            else
                dt = MachineFactory.GetLcrFrequencyTable19001();
            cboZRFreq.DisplayMember = dt.Columns[1].ColumnName;
            cboZRFreq.ValueMember = dt.Columns[0].ColumnName;
            cboZRFreq.DataSource = dt;
            if (dt.Rows.Count > 1) cboZRFreq.SelectedIndex = 1;
        }

        public void StartSerialPort()
        {
            try
            {
                if (!spLcr.IsOpen)
                {
                    spLcr.Open();
                }
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "容量表串口打开异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }

            try
            {
                if (!spLc.IsOpen)
                {
                    //spLc.Open();
                }
            }
            catch (Exception ex)
            {
                //QMessageBox.Show(ex.Message, "異常S0067", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }

            try
            {
                if (!spLc10.IsOpen)
                {
                    //spLc10.Open();
                }
            }
            catch (Exception ex)
            {
                //QMessageBox.Show(ex.Message, "異常S0067", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }

            try
            {
                if (!spBox.IsOpen)
                {
                    spBox.Open();
                }
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "通道盒子串口打开异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }

            //try
            //{
            //    if (!spBox2.IsOpen)
            //    {
            //        spBox2.Open();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    QMessageBox.Show(ex.Message, "通道盒子串口2打开异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    Logger.LogError(ex);
            //}
        }

        public void CloseSerialPort()
        {
            try
            {
                if (spLcr.IsOpen)
                {
                    spLcr.Close();
                    Thread.Sleep(300);
                }
            }
            catch (Exception ex)
            {
                //QMessageBox.Show(ex.Message, "容量表串口打开异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }


            try
            {
                if (spBox.IsOpen)
                {
                    spBox.Close();
                    Thread.Sleep(300);
                }
            }
            catch (Exception ex)
            {
                //QMessageBox.Show(ex.Message, "通道盒子串口打开异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }
        }

        private void BoxChecked_CheckedChanged(object sender, EventArgs e)
		{
            if (_IsAdjusting) return;

			try
			{
                StartSerialPort();
                Thread.Sleep(500);
                _IsAdjusting = true;
                CheckBox checkBox = sender as CheckBox;
				if (checkBox != null)
				{
					string sss = checkBox.Text;
					int id = int.Parse(sss);
					if (id <= 10)
					{
						bool check = checkBox.Checked;
                        box2.InitialAll();
                        Thread.Sleep(500);

                        if (chkLc.Checked)
                            box.LcTestChannel((byte)id, check);
                        else
						    box.LCRTestChannel((byte)id, check);
					}
                    else
                    {
                        bool check = checkBox.Checked;
                        box.InitialAll();
                        Thread.Sleep(500);

                        if (chkLc.Checked)
                            box2.LcTestChannel((byte)(id-10), check);
                        else
                            box2.LCRTestChannel((byte)(id-10), check);
                    }
				}
			}
			catch (Exception ex)
			{
				QMessageBox.Show(ex.Message,"異常S0064",MessageBoxButtons.OK,MessageBoxIcon.Error);
				Logger.LogError(ex);
			}
            finally
            {
                _IsAdjusting = false;
                CloseSerialPort();
                Thread.Sleep(500);
            }
		}


        private void btnMutilPage_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                StartSerialPort();
                Thread.Sleep(500);
                if (spLcr.IsOpen)
                {
                    lcrMeter.SetMutilMode(spLcr);
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0066", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _IsAdjusting = false;
                CloseSerialPort();
                Thread.Sleep(500);
            }
        }

        private void btnBasicPage_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                StartSerialPort();
                Thread.Sleep(500);
                if (spLcr.IsOpen)
                {
                    lcrMeter.SetSingleMode(spLcr);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0066", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _IsAdjusting = false;
                CloseSerialPort();
                Thread.Sleep(500);
            }
        }

        private void FormSet1601_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                //box.InitialAll();
                //Thread.Sleep(300);
                if(spBox.IsOpen)
                {
                    spBox.Close();
                    Thread.Sleep(300);
                }

                if(spLc.IsOpen)
                {
                    spLc.Close();
                    Thread.Sleep(300);
                }

                if (spLc10.IsOpen)
                {
                    spLc10.Close();
                    Thread.Sleep(300);
                }

                if (spLcr.IsOpen)
                {
                    spLcr.Close();
                    Thread.Sleep(300);
                }

                Application.DoEvents();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void btnInitialBox_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                StartSerialPort();
                Thread.Sleep(500);

                if (spBox.IsOpen)
                {
                    box.InitialAll();
                    Thread.Sleep(1500);
                    box2.InitialAll();
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0070", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _IsAdjusting = false;
                CloseSerialPort();
                Thread.Sleep(500);
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                if (QMessageBox.Show("即將進行開路校正，請確認","請確認",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;

                StartSerialPort();
                Thread.Sleep(500);

                _IsAdjusting = true;
                chkLc.Checked = false;
                //box.InitialAll();
                Thread.Sleep(200);
                box2.InitialAll();
                box.SwitchToLCR();
                Thread.Sleep(200);
                box.LCRTestChannel(1, true);
                Thread.Sleep(300);
                BackgroundWorker worker = new BackgroundWorker();
                this.Cursor = Cursors.WaitCursor;
                worker.DoWork += (s, a) =>
                {
                    lcrMeter.Open(spLcr);
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while (true)
                    {
                        if (stopwatch.Elapsed.TotalSeconds > 60) break;
                        Thread.Sleep(300);
                        string data = lcrMeter.GetData(spLcr);
                        if (!string.IsNullOrWhiteSpace(data))
                        {
                            string[] dataSplit = data.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                            if (dataSplit != null && dataSplit.Length > 0)
                            {
                                foreach (string ss in dataSplit)
                                {
                                    if (ss.Trim() == "1")
                                        return ;
                                }
                            }
                        }
                    }
                };
                worker.RunWorkerCompleted += (s, a)=>
                {
                    _IsAdjusting = false;
                    this.Cursor = Cursors.Default;
                    QMessageBox.Show("開路校正完成！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    CloseSerialPort();
                    Thread.Sleep(500);
                };
                worker.RunWorkerAsync();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0065", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnShort_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                if (QMessageBox.Show("即將進行短路校正，請確認", "請確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;

                StartSerialPort();
                Thread.Sleep(500);

                _IsAdjusting = true;
                chkLc.Checked = false;
                box.InitialAll();
                Thread.Sleep(200);
                box.SwitchToLCR();
                box2.InitialAll();
                Thread.Sleep(200);
                box.LCRTestChannel(1, true);
                Thread.Sleep(300);
                BackgroundWorker worker = new BackgroundWorker();
                this.Cursor = Cursors.WaitCursor;
                worker.DoWork += (s, a) =>
                {
                    lcrMeter.Short(spLcr);
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while (true)
                    {
                        if (stopwatch.Elapsed.TotalSeconds > 60) break;
                        Thread.Sleep(300);
                        string data = lcrMeter.GetData(spLcr);
                        if (!string.IsNullOrWhiteSpace(data))
                        {
                            string[] dataSplit = data.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                            if (dataSplit != null && dataSplit.Length > 0)
                            {
                                foreach (string ss in dataSplit)
                                {
                                    if (ss.Trim() == "1")
                                        return;
                                }
                            }
                        }
                    }
                };
                worker.RunWorkerCompleted += (s, a) =>
                {
                    _IsAdjusting = false;
                    this.Cursor = Cursors.Default;
                    QMessageBox.Show("短路校正完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    CloseSerialPort();
                    Thread.Sleep(500);
                };
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0065", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnBoxAdjustSingle_Click(object sender, EventArgs e)
        {
            chkLc.Checked = false;
            BoxAdjust(true);
        }

        //通道校正
        private void btnBoxAdjust_Click(object sender, EventArgs e)
        {
            chkLc.Checked = false;
            BoxAdjust(false);
        }


        BackgroundWorker worker;

        //停止
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (worker != null && worker.IsBusy && !worker.CancellationPending)
                    worker.CancelAsync();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        StringBuilder sb = new StringBuilder();
        /// <summary>
        ///  通道短路校正
        /// </summary>
        /// <param name="isSingle">是否单频校正</param>
        void BoxAdjust(bool isSingle)
        {
            if (_IsAdjusting) return;
            try
            {
                sb.Length = 0;
                if (isSingle && cboZRFreq.SelectedItem == null)
                {
                    QMessageBox.Show("請選擇要進行通道校正的頻率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboZRFreq.Focus();
                    return;
                }
                if (QMessageBox.Show("即將進行通道校正，請確認", "請確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;

                StartSerialPort();
                Thread.Sleep(500);

                //string freq = string.Empty;
                //DataRowView view = cboZRFreq.SelectedItem as DataRowView;
                //if (view != null)
                //{
                //    freq = view["Name"].ToString();
                //}
                string freq = FormCommon.GetDataTableComboBoxValue(cboZRFreq);
                int LcrFirstDelay = (int)numLcrFirstDelay.Value;
                int rxTestTimes = (int)numRxTestTimes.Value;
                int boxtime = (int)(numBox20Time.Value * 1000m);
                if (boxtime < 500) boxtime = 500;
                decimal cap, df, x, r;
                cap = df = x = r = 0;

                box.InitialAll();
                Thread.Sleep(boxtime);
                box2.InitialAll();
                Thread.Sleep(boxtime);
                btnMutilPage.PerformClick();
                StartSerialPort();
                Thread.Sleep(500);
                box.SwitchToLCR();
                Thread.Sleep(200);
                

                string freq1, freq2;
                freq2 = freq1 = string.Empty;

                DataTable table = cboZRFreq.DataSource as DataTable;
                if (table != null && table.Rows.Count > 0)
                    freq1 = table.Rows[0]["Value"].ToString();
                else return;
                freq2 = FormCommon.GetDataTableComboBoxValue(cboZRFreq);
                lcrMeter.SetFreq(spLcr, freq1, freq2, _TestItem);

                this.Cursor = Cursors.WaitCursor;
                worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                worker.WorkerSupportsCancellation = true;
                worker.DoWork += (s, a) =>
                {
                    _IsAdjusting = true;
                    for (int ii = 0; ii < table.Rows.Count; ii++)
                    {
                        if (!isSingle) freq = table.Rows[ii]["Value"].ToString();

                        if (worker.CancellationPending) break;
                         
                        sb.AppendLine(freq);
                        worker.ReportProgress(ii);
                        if (!isSingle) lcrMeter.SetFreq(spLcr, freq1, freq, _TestItem);
                        if (_LcrType == LcrType.FE2826A)
                        {
                            Thread.Sleep(500);
                            lcrMeter.Fetch(spLcr, _TestItem);
                        }
                        Thread.Sleep(200);
                        //通道循环
                        for (int i = 1; i < boxCount+1; i++)
                        {
                            if (worker.CancellationPending) break;


                            sb.AppendLine(i.ToString() + "start");
                            if (i < 11)
                            {
                                if (i == 1)
                                {
                                    box2.InitialAll();
                                    Thread.Sleep(boxtime);
                                }
                                box.LCRTestChannel((byte)i, true);
                                Thread.Sleep(100);
                            }
                            else
                            {
                                if (i == 11)
                                {
                                    box.InitialAll();
                                    Thread.Sleep(boxtime);
                                    box2.SwitchToLCR();
                                    Thread.Sleep(200);
                                }
                                box2.LCRTestChannel((byte)(i - 10), true);
                            }
                                if (LcrFirstDelay<1) Thread.Sleep(400);
                            if (i == 1 || i==11)
                            {
                                Thread.Sleep(LcrFirstDelay * 1000);
                            }

                            List<decimal> values = new List<decimal>();
                            for (int j = 0; j < rxTestTimes; j++)
                            {
                                decimal xTemp, rTemp;
                                if (_LcrType != LcrType.FE2826A)
                                    lcrMeter.Fetch(spLcr, _TestItem);
                                Thread.Sleep(460);
                                string data = lcrMeter.GetData(spLcr);
                                if (String.IsNullOrWhiteSpace(data)) continue;
                                sb.AppendLine("data:" + data);
                                if (lcrMeter.AnalysisData(data, out cap, out df, out xTemp, out rTemp, _TestItem, freq, true))
                                {
                                    x = xTemp;
                                    r = rTemp;
                                    values.Add(r);
                                }
                                sb.AppendLine("X:" + x.ToString());
                                sb.AppendLine("R:" + r.ToString());
                                Thread.Sleep(50);
                            }

                            //if (r != 0 || x != 0)
                            if(values.Count>2)
                            {
                                r = Tools.RemoveMaxMinThenAvg(values);
                                _OffsetCompute1601.SetOffsetEntity(freq, i, r, x);
                            }

                            if (i < 11)
                                box.LCRTestChannel((byte)i, false);
                            else
                            {
                                box2.LCRTestChannel((byte)(i - 10), false);
                            }

                            Thread.Sleep(250);
                            sb.AppendLine(i.ToString() + "end");

                            worker.ReportProgress(-1);
                        }

                        if (isSingle) break;
                    }
                    Logger.LogMessage(sb.ToString());
                    sb.Length = 0;
                };
                worker.ProgressChanged += (s, a) =>
                {
                    if (a.ProgressPercentage >= 0 && !isSingle) cboZRFreq.SelectedIndex = a.ProgressPercentage;
                    else BindingRXOffset(_CurrentEntity);
                };
                worker.RunWorkerCompleted += (s, a) =>
                {
                    _IsAdjusting = false;
                    box.InitialAll();
                    Thread.Sleep(boxtime);
                    box2.InitialAll();
                    Thread.Sleep(boxtime);
                    this.Cursor = Cursors.Default;
                    if (a.Error != null)
                        QMessageBox.ShowException(a.Error);
                    QMessageBox.Show("通道校正完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    CloseSerialPort();
                    Thread.Sleep(500);

                };
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0065", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSpeed_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                StartSerialPort();
                Thread.Sleep(500);

                if (spLcr.IsOpen)
                {
                    if (cboSpeed.SelectedItem == null) return;
                    lcrMeter.SetSpeed(spLcr,cboSpeed.SelectedItem.ToString());
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0070", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _IsAdjusting = false;
                CloseSerialPort();
                Thread.Sleep(500);
            }
        }

        private void cboZRFreq_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboZRFreq.SelectedItem == null)
            {
                BindingRXOffset(_EmptyOffsetEntity);
            }
            else
            {
                //DataRowView view = cboZRFreq.SelectedItem as DataRowView;
                //string freq = string.Empty;
                //if (view != null)
                //    freq = view["Name"].ToString();
                string freq = FormCommon.GetDataTableComboBoxValue(cboZRFreq);
                OffsetEntity1601 offsetEntity1601 = _OffsetCompute1601.GetOffsetEntity(freq);
                if(offsetEntity1601 == null)
                {
                    offsetEntity1601 = new OffsetEntity1601(freq);
                    _OffsetCompute1601.AddOffsetEntity(freq,offsetEntity1601);
                }

                _CurrentEntity = offsetEntity1601;
                BindingRXOffset(offsetEntity1601);
            }

        }

        void BindingRXOffset(OffsetEntity1601 offsetEntity1601)
        {
            txtRs1.DataBindings.Clear();
            txtRs2.DataBindings.Clear();
            txtRs3.DataBindings.Clear();
            txtRs4.DataBindings.Clear();
            txtRs5.DataBindings.Clear();
            txtRs6.DataBindings.Clear();
            txtRs7.DataBindings.Clear();
            txtRs8.DataBindings.Clear();
            txtRs9.DataBindings.Clear();
            txtRs10.DataBindings.Clear();
            txtXs1.DataBindings.Clear();
            txtXs2.DataBindings.Clear();
            txtXs3.DataBindings.Clear();
            txtXs4.DataBindings.Clear();
            txtXs5.DataBindings.Clear();
            txtXs6.DataBindings.Clear();
            txtXs7.DataBindings.Clear();
            txtXs8.DataBindings.Clear();
            txtXs9.DataBindings.Clear();
            txtXs10.DataBindings.Clear();

            txtRs11.DataBindings.Clear();
            txtRs12.DataBindings.Clear();
            txtRs13.DataBindings.Clear();
            txtRs14.DataBindings.Clear();
            txtRs15.DataBindings.Clear();
            txtRs16.DataBindings.Clear();
            txtRs17.DataBindings.Clear();
            txtRs18.DataBindings.Clear();
            txtRs19.DataBindings.Clear();
            txtRs20.DataBindings.Clear();
            txtXs11.DataBindings.Clear();
            txtXs12.DataBindings.Clear();
            txtXs13.DataBindings.Clear();
            txtXs14.DataBindings.Clear();
            txtXs15.DataBindings.Clear();
            txtXs16.DataBindings.Clear();
            txtXs17.DataBindings.Clear();
            txtXs18.DataBindings.Clear();
            txtXs19.DataBindings.Clear();
            txtXs20.DataBindings.Clear();

            txtROffset.DataBindings.Clear();
            txtZOffset.DataBindings.Clear();

            if (offsetEntity1601 != null)
            {
                txtRs1.DataBindings.Add("Text", offsetEntity1601, "Rs1");
                txtRs2.DataBindings.Add("Text", offsetEntity1601, "Rs2");
                txtRs3.DataBindings.Add("Text", offsetEntity1601, "Rs3");
                txtRs4.DataBindings.Add("Text", offsetEntity1601, "Rs4");
                txtRs5.DataBindings.Add("Text", offsetEntity1601, "Rs5");
                txtRs6.DataBindings.Add("Text", offsetEntity1601, "Rs6");
                txtRs7.DataBindings.Add("Text", offsetEntity1601, "Rs7");
                txtRs8.DataBindings.Add("Text", offsetEntity1601, "Rs8");
                txtRs9.DataBindings.Add("Text", offsetEntity1601, "Rs9");
               txtRs10.DataBindings.Add("Text", offsetEntity1601, "Rs10");
                txtXs1.DataBindings.Add("Text", offsetEntity1601, "Xs1");
                txtXs2.DataBindings.Add("Text", offsetEntity1601, "Xs2");
                txtXs3.DataBindings.Add("Text", offsetEntity1601, "Xs3");
                txtXs4.DataBindings.Add("Text", offsetEntity1601, "Xs4");
                txtXs5.DataBindings.Add("Text", offsetEntity1601, "Xs5");
                txtXs6.DataBindings.Add("Text", offsetEntity1601, "Xs6");
                txtXs7.DataBindings.Add("Text", offsetEntity1601, "Xs7");
                txtXs8.DataBindings.Add("Text", offsetEntity1601, "Xs8");
                txtXs9.DataBindings.Add("Text", offsetEntity1601, "Xs9");
               txtXs10.DataBindings.Add("Text", offsetEntity1601, "Xs10");

                txtRs11.DataBindings.Add("Text", offsetEntity1601, "Rs11");
                txtRs12.DataBindings.Add("Text", offsetEntity1601, "Rs12");
                txtRs13.DataBindings.Add("Text", offsetEntity1601, "Rs13");
                txtRs14.DataBindings.Add("Text", offsetEntity1601, "Rs14");
                txtRs15.DataBindings.Add("Text", offsetEntity1601, "Rs15");
                txtRs16.DataBindings.Add("Text", offsetEntity1601, "Rs16");
                txtRs17.DataBindings.Add("Text", offsetEntity1601, "Rs17");
                txtRs18.DataBindings.Add("Text", offsetEntity1601, "Rs18");
                txtRs19.DataBindings.Add("Text", offsetEntity1601, "Rs19");
                txtRs20.DataBindings.Add("Text", offsetEntity1601, "Rs20");
                txtXs11.DataBindings.Add("Text", offsetEntity1601, "Xs11");
                txtXs12.DataBindings.Add("Text", offsetEntity1601, "Xs12");
                txtXs13.DataBindings.Add("Text", offsetEntity1601, "Xs13");
                txtXs14.DataBindings.Add("Text", offsetEntity1601, "Xs14");
                txtXs15.DataBindings.Add("Text", offsetEntity1601, "Xs15");
                txtXs16.DataBindings.Add("Text", offsetEntity1601, "Xs16");
                txtXs17.DataBindings.Add("Text", offsetEntity1601, "Xs17");
                txtXs18.DataBindings.Add("Text", offsetEntity1601, "Xs18");
                txtXs19.DataBindings.Add("Text", offsetEntity1601, "Xs19");
                txtXs20.DataBindings.Add("Text", offsetEntity1601, "Xs20");
            }
        }

        private void btnClearRX_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;

            try 
            { 

                if (QMessageBox.Show("清除通道短路數據化無法恢復，請確認","請確認",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;

                if (_CurrentEntity != null)
                {
                    _CurrentEntity.Rs1 = 0;
                    _CurrentEntity.Rs2 = 0;
                    _CurrentEntity.Rs3 = 0;
                    _CurrentEntity.Rs4 = 0;
                    _CurrentEntity.Rs5 = 0;
                    _CurrentEntity.Rs6 = 0;
                    _CurrentEntity.Rs7 = 0;
                    _CurrentEntity.Rs8 = 0;
                    _CurrentEntity.Rs9 = 0;
                    _CurrentEntity.Rs10 = 0;

                    _CurrentEntity.Xs1 = 0;
                    _CurrentEntity.Xs2 = 0;
                    _CurrentEntity.Xs3 = 0;
                    _CurrentEntity.Xs4 = 0;
                    _CurrentEntity.Xs5 = 0;
                    _CurrentEntity.Xs6 = 0;
                    _CurrentEntity.Xs7 = 0;
                    _CurrentEntity.Xs8 = 0;
                    _CurrentEntity.Xs9 = 0;
                    _CurrentEntity.Xs10 = 0;

                    _CurrentEntity.Rs11 = 0;
                    _CurrentEntity.Rs12 = 0;
                    _CurrentEntity.Rs13 = 0;
                    _CurrentEntity.Rs14 = 0;
                    _CurrentEntity.Rs15 = 0;
                    _CurrentEntity.Rs16 = 0;
                    _CurrentEntity.Rs17 = 0;
                    _CurrentEntity.Rs18 = 0;
                    _CurrentEntity.Rs19 = 0;
                    _CurrentEntity.Rs20 = 0;

                    _CurrentEntity.Xs11 = 0;
                    _CurrentEntity.Xs12 = 0;
                    _CurrentEntity.Xs13 = 0;
                    _CurrentEntity.Xs14 = 0;
                    _CurrentEntity.Xs15 = 0;
                    _CurrentEntity.Xs16 = 0;
                    _CurrentEntity.Xs17 = 0;
                    _CurrentEntity.Xs18 = 0;
                    _CurrentEntity.Xs19 = 0;
                    _CurrentEntity.Xs20 = 0;

                    BindingRXOffset(_CurrentEntity);
                }
                
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                _IsAdjusting = false;
            }
        }

        private void txtRs1_Validating(object sender, CancelEventArgs e)
        {
            if (_IsAdjusting) e.Cancel = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;

            //if (!UserRightService.CheckRight("FormComSet", this._User, RightType.Modi))
            //{
            //    return;
            //}

            try
            {
                label17.Focus();
                _IsAdjusting = true;

                _OffsetCompute1601.SetLcFirstDelay((int)numLcFirstDelay.Value);
                _OffsetCompute1601.SetLcrFirstDelay((int)numLcrFirstDelay.Value);
                _OffsetCompute1601.SetTestTimes((int)numTestTimes.Value);
                _OffsetCompute1601.SetRxTestTimes((int)numRxTestTimes.Value);
                _OffsetCompute1601.SetChannelCount((int)numChannelCount.Value);

                //Box20Time
                _OffsetCompute1601.SetBox20Time(numBox20Time.Value);

                double zOffset = 0;
                if (double.TryParse(txtZOffset.Text, out zOffset))
                {
                    _OffsetCompute1601.SetZOffset(zOffset);
                }
                double rOffset = 0;
                if (double.TryParse(txtROffset.Text, out rOffset))
                {
                    _OffsetCompute1601.SetROffset(rOffset);
                }

                #region 通道禁用/启用
                _OffsetCompute1601.Enable1 = chkEnable1.Checked;
                _OffsetCompute1601.Enable2 = chkEnable2.Checked;
                _OffsetCompute1601.Enable3 = chkEnable3.Checked;
                _OffsetCompute1601.Enable4 = chkEnable4.Checked;
                _OffsetCompute1601.Enable5 = chkEnable5.Checked;
                _OffsetCompute1601.Enable6 = chkEnable6.Checked;
                _OffsetCompute1601.Enable7 = chkEnable7.Checked;
                _OffsetCompute1601.Enable8 = chkEnable8.Checked;
                _OffsetCompute1601.Enable9 = chkEnable9.Checked;
                _OffsetCompute1601.Enable10 = chkEnable10.Checked;
                _OffsetCompute1601.Enable11 = chkEnable11.Checked;
                _OffsetCompute1601.Enable12 = chkEnable12.Checked;
                _OffsetCompute1601.Enable13 = chkEnable13.Checked;
                _OffsetCompute1601.Enable14 = chkEnable14.Checked;
                _OffsetCompute1601.Enable15 = chkEnable15.Checked;
                _OffsetCompute1601.Enable16 = chkEnable16.Checked;
                _OffsetCompute1601.Enable17 = chkEnable17.Checked;
                _OffsetCompute1601.Enable18 = chkEnable18.Checked;
                _OffsetCompute1601.Enable19 = chkEnable19.Checked;
                _OffsetCompute1601.Enable20 = chkEnable20.Checked;
                #endregion

                _OffsetCompute1601.SaveOffset();

                QMessageBox.Show("保存成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                _IsAdjusting = false;
            }
        }

        private void FormSet1601_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Modifiers == (Keys.Control | Keys.Alt) && e.KeyCode == Keys.F5)
            {
                groupBox6.Visible = !groupBox6.Visible;
            }
        }

        private void chkLc_CheckedChanged(object sender, EventArgs e)
        {
            btnInitialBox_Click(btnInitialBox, new EventArgs());
            chk1.Checked = chk2.Checked = chk3.Checked = chk4.Checked = chk5.Checked
                 = chk6.Checked = chk7.Checked = chk8.Checked = chk9.Checked = chk10.Checked = false;
        }

        private void btnChannelData(object sender, EventArgs e)
        {
            if(new FormMachinePwdCheck().ShowDialog() == DialogResult.OK)
                groupBox6.Visible = true;
        }

        private void btnCloseVoice_Click(object sender, EventArgs e)
        {
            try
            {
                spLc.Open();
                Thread.Sleep(200);
                spLc10.Open();
                Thread.Sleep(200);

                Cursor = Cursors.WaitCursor;
                byte[] SendBytes = null;
                string SendData = "BUPP 0" + Environment.NewLine;
                SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
                spLc.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                Thread.Sleep(50);
                spLc10.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                MessageBox.Show("仪器声音已关闭");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
                spLc.Close();
                Thread.Sleep(200);
                spLc10.Close();
                Thread.Sleep(200);
            }
        }

        private void btnOpenVoice_Click(object sender, EventArgs e)
        {
            try
            {
                spLc.Open();
                Thread.Sleep(200);
                spLc10.Open();
                Thread.Sleep(200);

                Cursor = Cursors.WaitCursor;
                byte[] SendBytes = null;
                string SendData = "BUPP 1" + Environment.NewLine;
                SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
                spLc.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                Thread.Sleep(50);
                spLc10.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                MessageBox.Show("仪器声音已开启");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
                spLc.Close();
                Thread.Sleep(200);
                spLc10.Close();
                Thread.Sleep(200);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var formMutilMsgBox = new FormMutilMsgBox(string.Empty, string.Empty, sb.ToString());
            formMutilMsgBox.Show();
        }

        private void btnVersion_Click(object sender, EventArgs e)
        {
            if (_IsAdjusting) return;
            try
            {
                StartSerialPort();
                Thread.Sleep(500);
                if (spLcr.IsOpen)
                {
                    var msg = LcrMeter19001A.GetVersion(spLcr);
                    QMessageBox.Show(msg);
                }
                else
                {
                    QMessageBox.ShowError("串口打开异常");
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0066", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _IsAdjusting = false;
                CloseSerialPort();
                Thread.Sleep(500);
            }
        }
    }
}
